package com.zmn.oms.zmn.business.impl.order;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.biz.engineer.common.dro.distribute.EngineerSupportDistributeOrderDRO;
import com.zmn.biz.engineer.common.query.distribute.DistributeOrderSkillQuery;
import com.zmn.biz.engineer.common.query.distribute.EngineerSupportDistributeOrderQuery;
import com.zmn.biz.engineer.dubbo.interfaces.distribute.DistributeOrderAssistListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.business.impl.order.OrderBaseBServiceImpl;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.bo.order.GridCompanyQueryBO;
import com.zmn.oms.model.bo.order.VerifyOrderBO;
import com.zmn.oms.model.dto.order.GridCompanyInfoDTO;
import com.zmn.oms.model.dto.order.OrderDTO;
import com.zmn.oms.model.dto.order.zmn.FactoryUpdateOrderDTO;
import com.zmn.oms.model.dto.order.zmn.ZsNormalUpdateOrderDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.factory.OrderFactory;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.warranty.OrderWarranty;
import com.zmn.oms.model.entity.warranty.OrderWarrantyProduct;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.conf.workturn.biztype.PlatBizTypeService;
import com.zmn.oms.zmn.business.impl.open.OpenOrderBaseBServiceImpl;
import com.zmn.oms.zmn.business.interfaces.order.OrderVerifyBService;
import com.zmn.oms.zmn.business.interfaces.order.ZsOrderBService;
import com.zmn.oms.zmn.business.interfaces.work.OrderWorkAssignBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsDistributeWorkBService;
import com.zmn.pay.common.constant.PayConsts;
import com.zmn.sp.common.model.available.SpAvailableAreaCheckDIO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName ZsVerifyOrderBServiceImpl
 * @description:
 * @author: wangyanci
 * @create: 2021-07-23 15:25
 * @Version 1.0
 **/
@Slf4j
@Service
public class OrderVerifyBServiceImpl extends OrderBaseBServiceImpl implements OrderVerifyBService {

    @Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    private DistributeOrderAssistListRemoteService distributeOrderAssistListRemoteService;
    @Resource
    private PlatBizTypeService platBizTypeService;

    @Autowired
    private ZsOrderWorkBService zsOrderWorkBService;
    @Autowired
    private ZsOrderBService zsOrderBService;

    @Autowired
    private OrderWorkAssignBService orderWorkAssignBService;

    @Autowired
    private ZsDistributeWorkBService zsDistributeWorkBService;

    @Override
    public ResultDTO verifyNormalUpdateOrder(ZsNormalUpdateOrderDTO zsNormalUpdateOrderDTO) {
        // 获取修改数据
        try {
            OrderDTO orderDTOInfo = super.getUpdateOrderDTO(zsNormalUpdateOrderDTO);
            OrderDTO orderDTO = this.getDBOrderDTO(orderDTOInfo);

            // 派单撤回校验
            if (zsNormalUpdateOrderDTO.isVerifyDistributeBack()) {
                ResultDTO<String> isDistributeBack = this.verifyIsDistributeBack(orderDTO, true);
                if (isDistributeBack.isStatusBool()) {
                    return ResultDTO.success(VerifyOrderConsts.getMessage(isDistributeBack));
                }
            }
            boolean isGrid = zsDistributeWorkBService.isGridDistributeByConfig(orderDTOInfo.getOrderWork());
            if (!isGrid) {
                // 分单撤回校验
                if (zsNormalUpdateOrderDTO.isVerifyAssignBack()) {
                    ResultDTO<String> isAssignBack = this.verifyIsAssignBack(orderDTO);
                    if (isAssignBack.isStatusBool()) {
                        return ResultDTO.success(VerifyOrderConsts.getMessage(isAssignBack));
                    }
                }
            }
        } catch (OmsBaseException e) {
            ResultDTO.fail(e.getMessage());
        }
        return ResultDTO.success();
    }

    @Override
    public ResultDTO verifyFactoryUpdateOrder(FactoryUpdateOrderDTO factoryUpdateOrderDTO) {
        // 获取修改数据
        try {
            ZsNormalUpdateOrderDTO zsNormalUpdateOrderDTO = BeanMapper.map(factoryUpdateOrderDTO, ZsNormalUpdateOrderDTO.class);
            OrderDTO orderDTOInfo = super.getUpdateOrderDTO(zsNormalUpdateOrderDTO);
            OrderDTO orderDTO = this.getDBOrderDTO(orderDTOInfo);

            // 派单撤回校验
            if (factoryUpdateOrderDTO.isVerifyDistributeBack()) {
                ResultDTO<String> isDistributeBack = this.verifyIsDistributeBack(orderDTO, true);
                if (isDistributeBack.isStatusBool()) {
                    return ResultDTO.success(VerifyOrderConsts.getMessage(isDistributeBack));
                }
            }
            // 分单撤回校验
            if (factoryUpdateOrderDTO.isVerifyAssignBack()) {
                ResultDTO<String> isAssignBack = this.verifyIsAssignBack(orderDTO);
                if (isAssignBack.isStatusBool()) {
                    return ResultDTO.success(VerifyOrderConsts.getMessage(isAssignBack));
                }
            }
        } catch (OmsBaseException e) {
            ResultDTO.fail(e.getMessage());
        }
        return ResultDTO.success();
    }

    /**
     * 获取预付款提示，分单撤回、派单撤回、取消使用
     * @param orderId
     * @param workId
     * @return
     */
    @Override
    public String getAmountTips(Long orderId, Long workId) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        StringBuilder sb = new StringBuilder();
        sb.append("工单已有已支付");
        StringJoiner sj = new StringJoiner("、");
        boolean tip = false;
        boolean prepayAmountStatus = Objects.nonNull(orderWork.getPrepayAmount()) && Objects
                .equals(orderWork.getPrepayStatus(), PayConsts.PAY_STATUS_DONE);
        boolean depositAmountStatus = Objects.nonNull(orderWork.getDepositAmount()) && Objects
                .equals(orderWork.getDepositStatus(), PayConsts.PAY_STATUS_DONE);
        boolean channelPrepayAmountStatus = Objects.nonNull(orderWork.getChannelPrepayAmount()) && Objects
                .equals(orderWork.getChannelPrepayStatus(), PayConsts.PAY_STATUS_DONE);
        if (channelPrepayAmountStatus) {
            tip = true;
            sj.add("渠道代收");
        }
        if (prepayAmountStatus) {
            tip = true;
            sj.add("平台代收");
        }
        if (depositAmountStatus) {
            tip = true;
            sj.add("定金");
        }
        if (tip) {
            sb.append(sj.toString());
            sb.append("，请谨慎操作！");
            return sb.toString();
        } else {
            return null;
        }
    }

    @Override
    public ResultDTO verifyRework(Long orderId) {
        // 原单-返修卡是否过期
        OrderWarranty orderWarranty = orderWarrantyService.findByOrderId(orderId);
        if (orderWarranty != null && Objects.equals(OrderConsts.ORDER_WARRANTY_TYPE_CARD, orderWarranty.getType())) {
            List<OrderWarrantyProduct> orderWarrantyProductList = orderWarrantyProductService.listByOrderId(orderId);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(orderWarrantyProductList)) {
                List<OrderWarrantyProduct> collect = orderWarrantyProductList.stream()
                        .filter(e -> e.getExpiredTime() != null)
                        .collect(Collectors.toList());
                if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(collect)) {
                    boolean validTimeRange = collect.stream().anyMatch(e -> e.getExpiredTime().getTime() > DateUtil
                            .getNow().getTime());
                    if (!validTimeRange) {
                        return ResultDTO.fail("无效返修单号-保修卡已过期");
                    }
                }
            }
        }
        return ResultDTO.success();
    }

    @Override
    public VerifyOrderBO verifyUpdateOrderAll(OrderDTO orderDTOInfo, Boolean isGrid) {
        OrderDTO orderDTO = this.getDBOrderDTO(orderDTOInfo);
        VerifyOrderBO verifyOrderBO = new VerifyOrderBO();
        // 平台直派只校验派单撤回
        if (!isGrid) {
            verifyOrderBO.setIsAssignBack(this.verifyIsAssignBack(orderDTO));
        }
        verifyOrderBO.setIsDistributeBack(this.verifyIsDistributeBack(orderDTO, false));
        return verifyOrderBO;
    }

    @Override
    public ResultDTO<String> verifyIsDistributeBack(OrderDTO orderDTOInfo, Boolean beforeUpdate) {
        OrderDTO orderDTO = this.getDBOrderDTO(orderDTOInfo);
        // 订单信息
        OrderWork orderWork = orderDTO.getOrderWork();
        // 派单撤回
        ResultDTO<String> isDistributeBack = null;
        // 服务商派单修改不更新网格信息
        OrderWork configWork = new OrderWork();
        configWork.setPlatWork(orderDTO.getDbOrderWork().getPlatWork());
        configWork.setManageCompanyId(orderDTO.getDbOrderWork().getManageCompanyId());
        configWork.setCityId(orderWork.getCityId());
        configWork.setBizType(orderDTO.getDbOrderWork().getBizType());
        boolean isGrid = zsDistributeWorkBService.isGridDistributeByConfig(configWork);
        if (isGrid) {
            // 派单撤回
            isDistributeBack = this.isDistributeBack(orderDTO, isGrid, beforeUpdate);
        } else {
            // 是否撤回
            ResultDTO<String> needBackResult = this.needBack(orderDTO);
            // 派单撤回
            isDistributeBack = needBackResult != null ? needBackResult : this.isDistributeBack(orderDTO, isGrid, beforeUpdate);
        }
        // log处理
        isDistributeBack.setData(Optional.ofNullable(VerifyOrderConsts.backSwitch(isDistributeBack)).orElse(isDistributeBack.getData()));
        return isDistributeBack;
    }

    @Override
    public ResultDTO<String> verifyIsAssignBack(OrderDTO orderDTOInfo) {
        OrderDTO orderDTO = this.getDBOrderDTO(orderDTOInfo);

        // 分单撤回
        ResultDTO<String> isAssignBack = null;
        ResultDTO<String> needBackResult = this.needBack(orderDTO);
        // 分单撤回
        isAssignBack = needBackResult != null ? needBackResult : this.isAssignBack(orderDTO);

        // log处理
        isAssignBack.setData(Optional.ofNullable(VerifyOrderConsts.backSwitch(isAssignBack)).orElse(isAssignBack.getData()));
        return isAssignBack;
    }

    /**
     * 是否撤回
     * null，执行后续撤回判断
     * not null，返回是否撤回
     *
     * @param orderDTO
     * @return
     */
    private ResultDTO<String> needBack(OrderDTO orderDTO) {
        OrderWork dbOrderWork = orderDTO.getDbOrderWork();
        if (NumberUtil.isNullOrZero(dbOrderWork.getManageCompanyId())) {
            return null;
        }
        if (!CompanyConsts.INCLUDE_VIRTUAL_COMPANY_PLAT.contains(dbOrderWork.getPlatWork())) {
            return null;
        }
        Integer channelId = orderDTO.getOrderWork() != null ? orderDTO.getOrderWork().getChannelId() : 0;
        logger.debug("分单撤回，工单[{}]渠道[{}]", dbOrderWork.getWorkId(), channelId);

        boolean containsVirtualCompany = CompanyConsts.VIRTUAL_MANAGE_COMPANY_ID_LIST.contains(dbOrderWork.getManageCompanyId());
        if (Objects.equals(dbOrderWork.getPlatWork(), GlobalConsts.PLAT_MARK_ZMN)) {
            // 啄木鸟平台，要判断渠道
            if (!ChannelConsts.CHANNEL_ID_ASSIGN_VIRTUAL_COMANY_LIST.contains(channelId)) {
                return null;
            }
            logger.info("是虚拟公司-不撤回，否则撤回[{}]", containsVirtualCompany);
            return containsVirtualCompany ? ResultDTO.fail("虚拟公司不撤回") : ResultDTO.success("虚拟公司和渠道不一致，撤回");
        } else {
            logger.info("是否虚拟公司[{}]。是虚拟公司-不撤回，否则继续判断后续的分单，派单撤回条件", containsVirtualCompany);
            if (containsVirtualCompany) {
                return ResultDTO.fail("虚拟公司不撤回");
            } else {
                return null;
            }
        }
    }

    /**
     * 判断订单派单撤回
     *
     * @param orderDTO
     * @param isGrid   true网格化派单
     */
    private ResultDTO<String> isDistributeBack(OrderDTO orderDTO, Boolean isGrid, Boolean beforeUpdate) {
        OrderWork dbOrderWork = orderDTO.getDbOrderWork();
        OrderWork orderWork = orderDTO.getOrderWork();

        // 在：已派单or已领单or已上门-进行中状态，修改城市，还需派单撤回
        if (dbOrderWork.getStatus() < OrderStatusConsts.WORK_STATUS_DISTRIBUTE ||
                dbOrderWork.getStatus() > OrderStatusConsts.WORK_STATUS_VISIT
                || dbOrderWork.getResultStatus() != OrderStatusConsts.WORK_RESULT_DOING) {
            return ResultDTO.fail("状态判断");
        }

        if (isGrid) {
            if (!beforeUpdate) {
                // 总公司员工平台直派撤回判断
                if (!Objects.equals(orderDTO.getDbOrderDetail().getGridCompanyId(), orderDTO.getOrderDetail().getGridCompanyId())) {
                    return new ResultDTO(VerifyOrderConsts.DISTRIBUTEBACK_MASTER_GRID_COMPANY, true, "", "修改城市");
                }
            } else {
                GridCompanyQueryBO gridCompanyQueryBO = new GridCompanyQueryBO();
                gridCompanyQueryBO.setCityId(orderWork.getCityId());
                gridCompanyQueryBO.setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_PLAT);
                gridCompanyQueryBO.setLatitude(orderDTO.getOrderDetail().getLatitude());
                gridCompanyQueryBO.setLongitude(orderDTO.getOrderDetail().getLongitude());
                gridCompanyQueryBO.setServCategId(orderWork.getServCategId());
                gridCompanyQueryBO.setShowCategId(orderWork.getShowCategId());
                gridCompanyQueryBO.setShowCategOneId(orderWork.getShowCategOneId());
                gridCompanyQueryBO.setPreManageCompanyId(orderDTO.getPreManageCompanyId());
                gridCompanyQueryBO.setPlatWork(orderWork.getPlatWork());
                gridCompanyQueryBO.setOrderId(orderWork.getOrderId());
                GridCompanyInfoDTO gridCompanyInfo = zsOrderBService.getGridCompanyInfo(gridCompanyQueryBO);
                if (!Objects.equals(gridCompanyInfo.getGridCompanyId(), orderDTO.getDbOrderDetail().getGridCompanyId())) {
                    return new ResultDTO(VerifyOrderConsts.DISTRIBUTEBACK_MASTER_GRID_COMPANY, true, "", "行政子公司发生变更");
                }
            }
        }

        // 修改城市，派单撤回
        if (!Objects.equals(dbOrderWork.getCityId(), orderWork.getCityId())) {
            return new ResultDTO(VerifyOrderConsts.DISTRIBUTEBACK_MASTER_SERVICE_CITY, true, "", "修改城市");
        }

        // 不符合派单规则的，需要撤回

        //CannotDistributeOrderReasonQuery cannotDistributeOrderReasonQuery = new CannotDistributeOrderReasonQuery();
        EngineerSupportDistributeOrderQuery cannotDistributeOrderReasonQuery = new EngineerSupportDistributeOrderQuery();

        cannotDistributeOrderReasonQuery.setSerialNumber(UUID.randomUUID().toString());

        cannotDistributeOrderReasonQuery.setEngineerId(dbOrderWork.getMasterId());
        cannotDistributeOrderReasonQuery.setOriginalEngineerId(dbOrderWork.getReworkMasterId());
        cannotDistributeOrderReasonQuery.setPlat(dbOrderWork.getPlatWork());
        cannotDistributeOrderReasonQuery.setBizType(dbOrderWork.getBizType());
        cannotDistributeOrderReasonQuery.setSubCompanyId(dbOrderWork.getCompanyId());
        cannotDistributeOrderReasonQuery.setSpCompanyId(dbOrderWork.getManageCompanyId());
        cannotDistributeOrderReasonQuery.setChannelId(orderWork.getChannelId());
        cannotDistributeOrderReasonQuery.setCityId(orderWork.getCityId());
        cannotDistributeOrderReasonQuery.setDutyTime(orderWork.getDutyTime());

        // 是否网格化派单
        if (isGrid) {
            cannotDistributeOrderReasonQuery.setOrderLat(orderDTO.getOrderDetail().getLatitude());
            cannotDistributeOrderReasonQuery.setOrderLng(orderDTO.getOrderDetail().getLongitude());
            cannotDistributeOrderReasonQuery.setGridScreen(GlobalConsts.YES);
        }

        List<List<DistributeOrderSkillQuery>> servSkillLists = zsDistributeWorkBService.buildSkillQueryLists(orderWork.getProductId(),
                orderWork.getShowProductId(), orderWork.getServCategId(), orderWork.getCategId());
        cannotDistributeOrderReasonQuery.setServSkillList(servSkillLists);



        // 后门开关永远开
        Integer backDoorStatus = GlobalConsts.YES;
        //cannotDistributeOrderReasonQuery.setBackDoorStatus(backDoorStatus);
        cannotDistributeOrderReasonQuery.setSkipServAreaCheck(backDoorStatus);
        cannotDistributeOrderReasonQuery.setSkipOnlineCheck(backDoorStatus);

        log.info("校验是否派单撤回入参:[{}]", JSON.toJSONString(cannotDistributeOrderReasonQuery));
        //ResponseDTO<CannotDistributeOrderReasonDRO> responseDTO = engDistributeOrderListRemoteService.getCannotDistributeOrderReason(cannotDistributeOrderReasonQuery);
        // todo fubiao
        logger.info("isDistributeBack#checkEngineerSupportDistributeOrder 入参 [{}]",JSON.toJSONString(cannotDistributeOrderReasonQuery));
        ResponseDTO<EngineerSupportDistributeOrderDRO> responseDTO = distributeOrderAssistListRemoteService.checkEngineerSupportDistributeOrder(cannotDistributeOrderReasonQuery);
        logger.info("isDistributeBack#checkEngineerSupportDistributeOrder 出参 [{}]",JSON.toJSONString(responseDTO));
        log.info("校验是否派单撤回出参:[{}]", JSON.toJSONString(responseDTO));
        if (responseDTO.isSuccess() && responseDTO.getData() != null && Objects.equals(responseDTO.getData().getDistributeOrderStatus(), GlobalConsts.NO)) {
            return new ResultDTO(VerifyOrderConsts.DISTRIBUTEBACK_MASTER_ORDER_MASTER_SERVICE, true, "", responseDTO.getData().getNotDistributeOrderEnum().getName());
        }

        return ResultDTO.fail("满足技能");
    }

    /**
     * 订单分单撤回
     *
     * @param orderDTO
     * @return
     */
    private ResultDTO isAssignBack(OrderDTO orderDTO) {
        OrderDetail orderDetail = orderDTO.getOrderDetail();
        OrderWork orderWork = orderDTO.getOrderWork();
        OrderWork dbOrderWork = orderDTO.getDbOrderWork();
        if (dbOrderWork.getStatus() < OrderStatusConsts.WORK_STATUS_ASSIGN || dbOrderWork.getResultStatus() != OrderStatusConsts.WORK_RESULT_DOING) {
            return ResultDTO.fail("状态不满足-不撤回");
        }

        // 返修单不作分单撤回
        if (orderWork != null && Objects.equals(OrderConsts.ORDER_TYPE_REWORK, orderWork.getType())) {
            return ResultDTO.fail("返修单-不撤回");
        }

        // 校验平台开通业务类型
        log.debug("platBizTypeService.listBizTypeByPlat orderId={},platWork={}", orderWork.getOrderId(), orderWork.getPlatWork());
        List<Integer> listBizTypeByPlat = platBizTypeService.listBizTypeByPlat(orderWork.getPlatWork());
        log.debug("platBizTypeService.listBizTypeByPlat listBizTypeByPlat={}", listBizTypeByPlat);
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(listBizTypeByPlat)) {
            return new ResultDTO(VerifyOrderConsts.ASSIGNBACK_NOT_OPEN_BUSINESS, true, "", "当前平台未开通此业务类型");
        }
        if (!listBizTypeByPlat.contains(orderWork.getBizType())) {
            return new ResultDTO(VerifyOrderConsts.ASSIGNBACK_NOT_OPEN_BUSINESS, true, "", "当前平台未开通此业务类型");
        }

        // 检查平台是否开通服务分类
        boolean checkCategory = zsOrderWorkBService.checkOpenCategByPlatAndCateg(orderWork.getPlatWork(), orderWork.getServCategId(), orderWork.getShowCategId());
        if (!checkCategory) {
            return new ResultDTO(VerifyOrderConsts.ASSIGNBACK_SERVER_PRODUCT, true, "", "当前平台未开通此服务分类");
        }

        // 检测服务公司收款限制
        List<Integer> listCanServCompanyFilterPaymentLimit = orderWorkAssignBService.listCanServCompanyFilterPaymentLimit(Lists.newArrayList(dbOrderWork.getManageCompanyId()),
                dbOrderWork.getChannelId(),
                Optional.ofNullable(orderWork.getBizType()).orElse(com.zmn.consts.GlobalConsts.BIZ_TYPE_C));
        if (!listCanServCompanyFilterPaymentLimit.contains(dbOrderWork.getManageCompanyId())) {
            return new ResultDTO(VerifyOrderConsts.ASSIGNBACK_BALANCE_PAYMENT_LIMIT, true, "", "服务公司收款限制");
        }

        // 产品或者地址变更，判断已分单公司是否可以服务，不能服务，需要自动撤回
        SpAvailableAreaCheckDIO spAvailableAreaCheckDIO = new SpAvailableAreaCheckDIO();
        spAvailableAreaCheckDIO.setBizType(dbOrderWork.getBizType());
        spAvailableAreaCheckDIO.setManageCompanyId(dbOrderWork.getManageCompanyId());
        spAvailableAreaCheckDIO.setShowProductId(orderWork.getShowProductId());
        if (Objects.equals(orderDetail.getStreetSource(), OrderConsts.STREET_SOURCE_NONE) ||
                Objects.equals(orderDetail.getStreetSource(), OrderConsts.STREET_SOURCE_DEFAULT)) {
            spAvailableAreaCheckDIO.setStreetId(orderDetail.getStreetId());
        } else {
            spAvailableAreaCheckDIO.setStreetId(0);
        }
        spAvailableAreaCheckDIO.setLongitude(orderDetail.getLongitude());
        spAvailableAreaCheckDIO.setLatitude(orderDetail.getLatitude());

        // F单支持无经纬度可分单，如果不是F单，没有经纬度直接返回，不需要再调接口
        if (!Objects.equals(orderWork.getBizType(), com.zmn.consts.GlobalConsts.BIZ_TYPE_F) &&
                Objects.isNull(orderDetail.getLatitude()) && Objects.isNull(orderDetail.getLongitude())) {
            return new ResultDTO(VerifyOrderConsts.ASSIGNBACK_SERVER_AREA, true, "", "产品分类未开通或区域未开通");
        } else {
            spAvailableAreaCheckDIO.setCountyId(orderDetail.getCountyId());
        }

        logger.info("#oms#assign#isAssignBack# 入参：[{}] ", spAvailableAreaCheckDIO);
        ResponseDTO<Boolean> responseDTO = availableAreaListRemoteService.checkSpAvailableArea(spAvailableAreaCheckDIO);
        logger.info("#oms#assign#isAssignBack# 出参：[{}]", responseDTO);

        if (responseDTO.isSuccess() && responseDTO.getData()) {
            return ResultDTO.fail("满足服务返回-不撤回");
        }

        return new ResultDTO(VerifyOrderConsts.ASSIGNBACK_SERVER_AREA, true, "", "产品分类未开通或区域未开通");
    }

    /**
     * 获取原始数据
     *
     * @param orderDTO
     * @return
     */
    private OrderDTO getDBOrderDTO(OrderDTO orderDTO) {
        OrderDTO newOrderDTO = BeanMapper.map(orderDTO, OrderDTO.class);
        // 订单信息
        OrderWork orderWork = newOrderDTO.getOrderWork();

        // 原始数据
        OrderWork dbOrderWork = Optional.ofNullable(newOrderDTO.getDbOrderWork())
                .orElse(orderWorkService.findOrderWorkByKey(orderWork.getOrderId(), orderWork.getWorkId()));
        OrderFactory dbOrderFactory = Optional.ofNullable(newOrderDTO.getDbOrderFactory())
                .orElse(orderFactoryService.findOrderFactoryByKey(orderWork.getOrderId()));
        List<OrderProduct> dbOrderProductList = Optional.ofNullable(newOrderDTO.getDbOrderProductList())
                .orElse(orderProductService.listOrderProductByOrderId(orderWork.getOrderId()));
        OrderDetail dbOrderWorkDetail = Optional.ofNullable(newOrderDTO.getDbOrderDetail())
                .orElse(orderDetailService.findOrderDetailByKey(orderWork.getOrderId()));

        // 原始数据 赋值到 newOrderDTO
        newOrderDTO.setDbOrderWork(dbOrderWork);
        newOrderDTO.setDbOrderDetail(dbOrderWorkDetail);
        newOrderDTO.setDbOrderFactory(dbOrderFactory);
        newOrderDTO.setDbOrderProductList(dbOrderProductList);
        return newOrderDTO;
    }
}